package as2.controller;

// Import required java libraries
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import as2.model.OrderService;
import as2.model.UserService;
import as2.model.pojo.Order;
import as2.model.pojo.User;

// Extend HttpServlet class
public class FinalCheckout extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Method to handle GET method request.
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Order order = null;
		String cart = (String) request.getSession().getAttribute("cart");
		String city = (String) request.getSession().getAttribute("addressCity");
		Double shippingcost = (Double) request.getSession().getAttribute(
				"shippingcost");
		User user = (User) request.getSession().getAttribute("userObj");
		try {
			JSONArray cartJSON = new JSONArray(cart);
			order = assembleOrder(cartJSON);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		order.setShippingCost(shippingcost);
		order.setUser(user);
		order.setAddressCity(city);

		OrderService.save(order);
		UserService.update(user);
		JSONObject j2 = new JSONObject(user);
		request.getSession().setAttribute("user", j2.toString());
		request.getSession().setAttribute("userObj", user);
	}

	private Order assembleOrder(JSONArray itemList) throws JSONException {
		Order order = new Order();
		JSONObject item;
		Double price = 0.0;

		for (int i = 0; i < itemList.length(); i++) {
			item = itemList.getJSONObject(i);
			order.addItems(item.getString("id"), 1);
			price += item.getString("tags").split(" ").length;
		}

		order.setItemCost(price);

		return order;
	}

	// Method to handle POST method request.
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}